package database.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

    private String driverClassName = "org.apache.derby.jdbc.EmbeddedDriver";

    private String URL = "jdbc:derby:c:/temp/przychodnia-derby;create=true";

    private boolean driverIsPrepared = false;

    private Connection connection;

    /**
     * Metoda przygotowywujaca do nawiazania polaczenia z serverem, kontroluje czy zostanie utworzony sterownik
     */
    private void prepareDriver() {
        try {
            Class.forName(driverClassName).newInstance();
            driverIsPrepared = true;
        } catch (ClassNotFoundException e) {
            System.out.println("Błąd: " + e);
        } catch (InstantiationException e) {
            System.out.println("Błąd: " + e);
        } catch (IllegalAccessException e) {
            System.out.println("Błąd: " + e);
        }
    }

    /**
     * Metoda tworzaca i sprawdzajaca polaczenie z baza danych
     */
    public void createConnectionWithServer() {
        if (!isConnected()) {
            try {
                if (!driverIsPrepared) {
                    prepareDriver();
                }
                connection = DriverManager.getConnection(URL);
            } catch (SQLException e) {
                System.out.println("Nie mozna polaczyc sie z baza: " + URL);
            }
        }
    }

    public Connection getConnection() {
        createConnectionWithServer();
        return connection;
    }

    public boolean isConnected() {
        try {
            return connection != null && !connection.isClosed();
        } catch (SQLException e) {
            System.out.println("Połączenie nie otwarte");
        }
        return false;
    }
}
